package com.apes.framework.plugin.log.timer;

import com.apes.framework.util.ReflectUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

/**
 * 功能：任务执行计时器
 *
 * @author xul
 * @create 2018-04-20 13:33
 */
@Aspect
@Component
public class TimerExecutor {
    protected final Logger logger = LogManager.getLogger(TimerExecutor.class);

    @Around(value = "@annotation(timer)")
    public <T> T exec(ProceedingJoinPoint point, Timer timer) throws Throwable {
        Object[] args = point.getArgs();
        String describe = getDescribe(timer, args);

        long beginTime = System.nanoTime(); /**单位：微秒**/
        try {
            T result = (T) point.proceed();
            return result;
        } finally {
            long endTime = System.nanoTime();
            LogTimer.debug(describe, beginTime, endTime);
        }
    }

    private String getDescribe(Timer timer, Object[] args) {
        String arg = getArg(args);
        return timer.value() + (arg == null ? "" : "：" + arg);
    }

    private String getArg(Object[] args) {
        String arg = null;
        if (args.length == 1 && ReflectUtil.isPrimitive(args[0].getClass())) {
            arg = String.valueOf(args[0]);
        }
        return arg;
    }

}
